<template>
  <el-row class="client-info-box" v-loading="isLoading" element-loading-text="数据加载中...">
    <el-col :span="12" class="flex-column base-info">
      <el-row style="margin-bottom: 20px">
        <el-col :span="6">
          <title-view title="基本信息" />
        </el-col>
        <el-col :span="18" class="options-button">
          <el-button style="width: 80px" type="primary" @click="handelEdit" v-if="isDisable">编辑</el-button>
          <el-button style="width: 80px" type="primary" v-else @click="handelSave">保存</el-button>
          <template v-if="myClientForm.isOperate">
            <el-button type="primary" plain @click="handelLoseApply">流失申请</el-button>
            <el-button style="width: 80px" type="danger" plain @click="handelLoseDel">删除</el-button>
          </template>
        </el-col>
      </el-row>
      <div class="flex-overflow base-form-info">
        <el-form ref="ruleBaseFormRef" :model="myClientForm" :rules="addClientFormRules" label-width="100px" status-icon>
          <el-form-item label="客户姓名" prop="customerName">
            <el-input :disabled="isDisable" v-model.trim="myClientForm.customerName" />
          </el-form-item>
          <el-form-item label="电话" prop="mobileCode">
            <el-input :disabled="isDisable" :maxlength="11" clearable v-model.number="myClientForm.mobileCode" />
          </el-form-item>
          <el-form-item label="备用电话1">
            <el-input :disabled="isDisable" :maxlength="11" clearable v-model.number="myClientForm.mobileCode1" />
          </el-form-item>
          <el-form-item label="备用电话2">
            <el-input :disabled="isDisable" :maxlength="11" clearable v-model.number="myClientForm.mobileCode2" />
          </el-form-item>
          <el-form-item label="装修区域">
            <el-cascader
              ref="cascaderRef"
              :props="{
                label: 'name',
                value: 'cityCode'
              }"
              v-model="myClientForm.fitmentAreaIds"
              @change="handelChangeFitmentArea"
              :disabled="isDisable"
              :options="addressData"
              clearable
            />
          </el-form-item>
          <el-form-item label="小区名称" prop="residence">
            <el-input
              v-model.trim="myClientForm.residence"
              :autosize="{ minRows: 1 }"
              :disabled="isDisable"
              type="textarea"
              placeholder="小区名称"
              @change="handelChangeCommunityName"
            />
          </el-form-item>
          <el-form-item label="楼栋号">
            <el-input :disabled="isDisable" v-model="myClientForm.buildingName" @change="handelChangeBuildingName" />
          </el-form-item>
          <el-form-item label="项目地址">
            <el-input
              v-model="myClientForm.address"
              :autosize="{ minRows: 1 }"
              :disabled="isDisable"
              type="textarea"
              placeholder="项目地址"
            />
          </el-form-item>
          <el-form-item label="房屋面积">
            <el-input :disabled="isDisable" type="number" v-model.number="myClientForm.area" />
          </el-form-item>
          <el-form-item label="房屋总价等级">
            <el-select :disabled="isDisable" v-model="myClientForm.totalPriceLevel" @change="changeTotalPriceLevel">
              <el-option v-for="item in totalPriceLevels" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户来源">
            <el-select :disabled="isDisable" v-model="myClientForm.fromType" @change="changeFromType">
              <el-option v-for="item in source_classification" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="细分渠道">
            <el-select :disabled="isDisable" v-model="myClientForm.fromDetailType" @change="changeFromDetailType">
              <el-option
                v-for="item in fromDetails"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房屋类型">
            <el-select :disabled="isDisable" v-model="myClientForm.houseType" @change="changeHouseType">
              <el-option v-for="item in crm_house_types" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="装修用途">
            <el-checkbox-group :disabled="isDisable" v-model="myClientForm.fitment" @change="changeFitment">
              <el-checkbox v-for="item in crm_fitments" :key="item.value" :value="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!--<el-form-item label="业务类型">-->
          <el-form-item label="装修类型">
            <el-select :disabled="isDisable" v-model="myClientForm.businessType" @change="changeBusinessType">
              <el-option v-for="item in crm_business_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户预算">
            <el-select :disabled="isDisable" v-model="myClientForm.budget" @change="changeBudget">
              <el-option v-for="item in customerBudgets" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否期房">
            <el-radio-group :disabled="isDisable" v-model="myClientForm.isFutures">
              <el-radio value="1" size="large">是</el-radio>
              <el-radio value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              :disabled="isDisable"
              v-model="myClientForm.remark"
              :autosize="{ minRows: 4 }"
              :maxlength="200"
              show-word-limit
              type="textarea"
              placeholder="备注"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <el-col :span="12" class="flex-column follow-up-info">
      <el-row style="margin-bottom: 20px">
        <el-col :span="12">
          <title-view title="跟进记录" />
        </el-col>
        <el-col :span="12" class="options-button" v-show="myClientForm.isOperate">
          <el-button type="primary" @click="handelFollowUp">客户跟进</el-button>
        </el-col>
      </el-row>
      <div class="flex-overflow timeline-container">
        <time-line v-if="crmCustomerTrackList.length" :list="crmCustomerTrackList" />
        <el-empty v-else class="position-center" />
      </div>
    </el-col>
  </el-row>

  <!--  流失申请  -->
  <div class="lose-apply-dialog">
    <el-dialog v-model="isLoseApply" width="474" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <title-view title="流失申请"></title-view>
      </template>
      <el-form ref="loseApplyFormRef" :model="loseApplyForm" :rules="loseApplyRules" label-width="80px" status-icon>
        <el-form-item label="流失原因" prop="lostReason">
          <el-select v-model="loseApplyForm.lostReason">
            <el-option v-for="item in crm_reasons_loss" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期" prop="applyDate" required>
          <el-input disabled v-model="loseApplyForm.applyDate"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="loseApplyForm.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            show-word-limit
            :maxlength="200"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelLoseApplyClose" size="default">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelLoseApplySubmit" size="default">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!--  删除  -->
  <div class="client-del-dialog">
    <el-dialog v-model="isDeleteClient" width="400" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <div class="client-del-name">{{ myClientForm.customerName }}</div>
      <div class="client-del-tip">您确定要删除该客户？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelDelClose" size="default">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelDelSubmit" :loading="isDelLoading" size="default"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>

  <!--  客户跟进  -->
  <div class="follow-up-dialog">
    <el-dialog v-model="isFollowUp" width="540" align-center :show-close="false" :close-on-click-modal="false" destroy-on-close>
      <template #header>
        <title-view title="客户跟进"></title-view>
      </template>
      <el-form ref="fllowUpFormRef" v-if="isFollowUp" :model="fllowUpForm" :rules="fllowUpRules" label-width="110px" status-icon>
        <el-form-item label="跟进类型" prop="trackType">
          <el-select v-model="fllowUpForm.trackType">
            <el-option v-for="item in fllowUpTypes" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="trackDatetime">
          <el-input disabled v-model="fllowUpForm.trackDatetime"></el-input>
        </el-form-item>
        <el-form-item label="跟进内容" prop="contentDesc">
          <el-input
            v-model="fllowUpForm.contentDesc"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            show-word-limit
            :maxlength="200"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <ali-oss-upload
            :folder="defaultConfig.fileFolder"
            :fileList="upImagesList"
            :maxSize="10"
            :maxLength="8"
            file-tip="注：最多可上传8张，单张不超过10M，支持JPG/JPEG/PNG格式"
            :accept="accept"
            multiple
            list-type="picture-card"
            @uploadSuccess="uploadSuccess"
            @removeFile="removeFile"
          ></ali-oss-upload>
        </el-form-item>
        <el-form-item label="下次跟进设置">
          <el-switch v-model="fllowUpForm.isNextSetting" @change="changeNextSetting"></el-switch>
        </el-form-item>
        <template v-if="fllowUpForm.isNextSetting">
          <el-form-item label="下次跟进时间" :rules="{ required: true, message: '请选择下次跟进时间', trigger: 'change' }">
            <el-date-picker
              v-model="fllowUpForm.nextDateTine"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :disabled-date="datePicker.disabledDate"
              :disabled-hours="datePicker.disabledHour"
              :disabled-minutes="datePicker.disabledMinute"
              :disabled-seconds="datePicker.disabledSecond"
              @change="changeNextTime"
            />
          </el-form-item>
          <el-form-item label="提醒时间">
            <el-date-picker
              v-model="fllowUpForm.nextTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :disabled-date="datePicker.disabledDate"
              :disabled-hours="datePicker.disabledHour"
              :disabled-minutes="datePicker.disabledMinute"
              :disabled-seconds="datePicker.disabledSecond"
            />
          </el-form-item>
          <el-form-item label="提醒内容">
            <el-input
              v-model="fllowUpForm.nextContent"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              show-word-limit
              :maxlength="200"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="跟进任务"
            prop="stageTaskId"
            :rules="{ required: true, message: '请选择跟进任务', trigger: 'change' }"
          >
            <el-select v-model="fllowUpForm.stageTaskId" @change="handleTaskChange($event)">
              <el-option v-for="item in followOptions" :key="item.stageTaskId" :label="item.taskName" :value="item.stageTaskId" />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="提醒人">-->
          <!--            <el-select-->
          <!--              v-model="fllowUpForm.nextUserIdsList"-->
          <!--              multiple-->
          <!--              filterable-->
          <!--              remote-->
          <!--              reserve-keyword-->
          <!--              placeholder="请输入名称"-->
          <!--              :remote-method="searchUserRemoteMethod"-->
          <!--              :loading="searchUserLoading"-->
          <!--            >-->
          <!--              <el-option v-for="item in searchUserList" :key="item.userId" :label="item.nickName" :value="item.userId" />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelFollowUpClose" size="default">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelFollowUpSubmit" size="default">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, ref, watch } from "vue";
import { dayjs } from "element-plus";
import useAddressByKeyword from "@/hooks/AMap/useAddressByKeyword";
import addressData from "@/assets/pca-code";
import defaultConfig from "@/settings";
import * as datePicker from "@/utils/disabledOldDate";
import { dictList, getBudget } from "@/apis/dict/dict";
import { addClientFormInit, addClientFormRules } from "@/views/client/utils/config";
import useUserStore from "@/store/modules/user";
import { addTrack, applyLoss, clientInfoAndFollow, deleteClientInfo, editClientInfo, followTaskList } from "@/apis/myClient";
import { searchUser } from "@/apis/user";

import { microAppForceSendData } from "@/microApp";
import useTagsViewStore from "@/store/modules/tagsView";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["backList"]);

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const tagsViewStore = useTagsViewStore();

//运营平台字典—— 业务类型、房屋类型、装修用途、客户来源
const { crm_business_type, crm_house_types, crm_fitments, source_classification } = proxy.$dict(
  defaultConfig.dicts.crm_business_type,
  defaultConfig.dicts.crm_house_types,
  defaultConfig.dicts.crm_fitments,
  defaultConfig.dicts.source_classification
);
// saas租户自定义字典——房屋总价等级
const getDictData = async () => {
  const { data } = await dictList({ dictType: defaultConfig.dicts.HOUSE_PRICE_TYPE });
  totalPriceLevels.value = data || [];
  console.log(data, "<<<房屋总价等级");
};
/**
 * 根据业务类型查询客户预算
 * 根据客户来源查询细分渠道
 */
const customerBudgets = ref([]);
const fromDetails = ref([]);
const getCustomerSource = async () => {
  const postData = {
    dictType: defaultConfig.dicts.COSTEM_PREPRICE,
    dictLabel: myClientForm.value.businessTypeName
  };
  const { data } = await getBudget(postData);
  customerBudgets.value = data || [];
};
const getFromDetailTypes = async () => {
  const postData = {
    dictType: defaultConfig.dicts.COSTEM_ORIGIN,
    dictLabel: myClientForm.value.fromTypeName
  };
  const { data } = await getBudget(postData);
  fromDetails.value = data || [];
};

/**
 * 详情
 */
const isLoading = ref(false);
const getClientInfoAndFollow = () => {
  isLoading.value = true;
  clientInfoAndFollow(props.customerId)
    .then(res => {
      const { data } = res;
      myClientForm.value = data;
      myClientForm.value.isFutures = `${data.isFutures}`;
      myClientForm.value.fitment = data.fitment?.split(",") || [];
      myClientForm.value.fitmentAreaIds = data.fitmentAreaIds?.split(",") || [];
      const crmCustomerTrackListData = data?.crmCustomerTrackList || [];
      crmCustomerTrackList.value = crmCustomerTrackListData.map(item => {
        item.roleName = `${item.roleName}  ${item.updateBy}`;
        fllowUpTypes.value.some(subItem => {
          if (item.trackType === subItem.dictCode) {
            item.trackTypeName = subItem.dictLabel;
            return true;
          }
        });
        return item;
      });
      getCustomerSource();
      getFromDetailTypes();
    })
    .finally(() => {
      isLoading.value = false;
    });
};

/**
 * 编辑
 */
const isDisable = ref(true);
const myClientForm = ref({
  ...addClientFormInit,
  crmCustomerTrackList: []
});
const crmCustomerTrackList = ref([]);
const handelEdit = () => {
  isDisable.value = false;
};
const handelSave = () => {
  proxy.$refs.ruleBaseFormRef.validate(val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    const postData = {
      ...myClientForm.value,
      isFuturesName: myClientForm.value.isFutures === "1" ? "是" : "否",
      fitment: myClientForm.value.fitment?.join(",") || "",
      fitmentAreaIds: myClientForm.value.fitmentAreaIds?.join(",") || ""
    };
    editClientInfo(postData)
      .then(() => {
        isDisable.value = true;
        const customerInfo = { customerName: myClientForm.value.customerName, residence: myClientForm.value.residence };
        tagsViewStore.isRefresh = true;
        microAppForceSendData({ customerInfo });
        proxy.$modal.msgSuccess("更新成功");
      })
      .catch(() => {});
  });
};
// 区域
const addressCity = ref("");
const handelAreaInfo = () => {
  const nodeLabel = proxy.$refs.cascaderRef.getCheckedNodes();
  if (nodeLabel?.length) {
    const [province, city, county] = nodeLabel[0].pathLabels;
    addressCity.value = ["县", "市辖区"].includes(city) ? `${province}${county}` : `${province}${city}${county}`;
  }
};
const handelChangeFitmentArea = () => {
  handelAreaInfo();
  // myClientForm.value.residence = "";
  myClientForm.value.address = `${addressCity.value}${myClientForm.value.residence}${myClientForm.value.buildingName}`;
};
// 小区名称
const handelChangeCommunityName = () => {
  myClientForm.value.address = `${addressCity.value}${myClientForm.value.residence}${myClientForm.value.buildingName}`;
};
// const handelChangeResidence = () => {
//   myClientForm.value.address = `${addressCity.value}${myClientForm.value.residence}${myClientForm.value.buildingName}`;
// };
// 楼栋号
const handelChangeBuildingName = () => {
  myClientForm.value.address = `${addressCity.value}${myClientForm.value.residence}${myClientForm.value.buildingName}`;
};
//  房屋总价等级
const totalPriceLevels = ref([]);
const changeTotalPriceLevel = data => {
  const totalPriceLevel = totalPriceLevels.value.find(item => item.dictCode === data);
  myClientForm.value.totalPriceLevelName = totalPriceLevel?.dictLabel ?? "";
};
// 客户来源
const changeFromType = data => {
  const fromType = source_classification.value.find(item => item.value === data);
  myClientForm.value.fromTypeName = fromType?.label ?? "";
  myClientForm.value.fromDetailType = "";
  myClientForm.value.fromDetailTypeName = "";
  getFromDetailTypes();
};
// 细分渠道
const changeFromDetailType = data => {
  const fromDetail = fromDetails.value.find(item => item.dictCode === data);
  myClientForm.value.fromDetailTypeName = fromDetail.dictLabel;
};
// 房屋类型
const changeHouseType = data => {
  const houseType = crm_house_types.value.find(item => item.value === data);
  myClientForm.value.houseTypeName = houseType?.label ?? "";
};
// 装修用途
const changeFitment = data => {
  const fitmentName = data.reduce((pre, cur) => {
    const fitments = crm_fitments.value.find(subItem => {
      return subItem.value === cur;
    });
    fitments?.label && pre.push(fitments?.label);
    return pre;
  }, []);
  myClientForm.value.fitmentName = fitmentName?.join(",") || "";
};
// 业务类型
const changeBusinessType = data => {
  const houseType = crm_business_type.value.find(item => item.value === data);
  myClientForm.value.businessTypeName = houseType?.label ?? "";
  myClientForm.value.budgetName = "";
  myClientForm.value.budget = "";
  getCustomerSource();
};
// 客户预算
const changeBudget = data => {
  const customerBudget = customerBudgets.value.find(item => item.dictCode === data);
  myClientForm.value.budgetName = customerBudget?.dictLabel ?? "";
};

/**
 * 根据所选省市区搜索地址
 */
const addressList = ref([]);
const isLoadingSearch = ref(false);
const getAddress = async keyWord => {
  try {
    if (!keyWord) {
      return (addressList.value.length = 0);
    }
    isLoadingSearch.value = true;
    const autoOptions = {
      city: addressCity.value,
      citylimit: true,
      pageSize: 1000,
      extensions: "base"
    };
    addressList.value = await useAddressByKeyword(autoOptions, `${addressCity.value}${keyWord}`);
    isLoadingSearch.value = false;
  } catch (err) {
    isLoadingSearch.value = false;
  }
};
const handelSearchAddress = proxy.$lodash.debounce(getAddress, 500);

/**
 * 流失申请
 */
const isLoseApply = ref(false);
const loseApplyForm = ref({
  deptId: userStore.userInfo.mainDeptId,
  applyDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  remark: "",
  lostReason: ""
});
const loseApplyRules = {
  lostReason: { required: true, message: "流失原因不能为空", trigger: "change" },
  applyDate: { required: true, message: "申请日期不能为空", trigger: "blur" }
};
// 运营平台字典——流失原因
const { crm_reasons_loss } = proxy.$dict(defaultConfig.dicts.crm_reasons_loss);
const handelLoseApply = () => {
  isLoseApply.value = true;
};
const handelLoseApplySubmit = () => {
  proxy.$refs.loseApplyFormRef.validate(async valid => {
    if (!valid) {
      return proxy.$modal.msgError("请完善信息");
    }
    console.log(loseApplyForm.value, "<<<<流失申请");
    await applyLoss(loseApplyForm.value, props.customerId);
    proxy.$modal.msgSuccess("流失申请成功");
    handelLoseApplyClose();
  });
};
const handelLoseApplyClose = async () => {
  await nextTick();
  proxy.$refs.loseApplyFormRef.resetFields();
  isLoseApply.value = false;
  loseApplyForm.value = {
    deptId: userStore.userInfo.mainDeptId,
    applyDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    remarks: "",
    lostReason: ""
  };
};

/**
 * 删除
 */
const isDeleteClient = ref(false);
const isDelLoading = ref(false);
const handelLoseDel = () => {
  isDeleteClient.value = true;
};
const handelDelSubmit = () => {
  isDelLoading.value = true;
  deleteClientInfo(myClientForm.value.customerId)
    .then(() => {
      isDelLoading.value = false;
      isDeleteClient.value = false;
      tagsViewStore.isRefresh = true;
      proxy.$modal.msgSuccess("删除成功");
      emit("backList");
    })
    .catch(() => {
      isDelLoading.value = false;
    });
};
const handelDelClose = () => {
  isDeleteClient.value = false;
};

/**
 * 客户跟进
 */
const isFollowUp = ref(false);
const upImagesList = ref([]);
const accept = ".jpg,.JPG,.jpeg,.JPEG,.png,.PNG";
const fllowUpForm = ref({
  customerId: props.customerId,
  trackType: "",
  trackDatetime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  contentDesc: "",
  crmFileCreateVOList: [],
  isNextSetting: 0,
  nextDateTine: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  nextTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  nextContent: "",
  // nextUserIdsList: [],
  stageTaskId: ""
});
const fllowUpRules = {
  trackType: { required: true, message: "跟进类型不能为空", trigger: "change" },
  trackDatetime: { required: true, message: "跟进时间不能为空", trigger: "blur" },
  contentDesc: { required: true, message: "跟进内容不能为空", trigger: "blur" }
};
const fllowUpTypes = ref([]);
// 租户自定义字典——客户跟进类型
const getFllowUpType = async () => {
  const { data = [] } = await dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
  console.log(data, "<<<<<跟进类型");
  fllowUpTypes.value = data;
};
const handelFollowUp = () => {
  isFollowUp.value = true;
  getFollowList();
  // searchUserList.value = [
  //   {
  //     userId: userStore.userInfo.userId,
  //     nickName: userStore.userInfo.nickName
  //   }
  // ];
  // fllowUpForm.value.nextUserIdsList = [userStore.userInfo.userId];
};
const uploadSuccess = data => {
  upImagesList.value.push({ fileUrl: data.fileUrl });
};
const removeFile = file => {
  upImagesList.value.splice(file.index, 1);
};
//下次跟进时间
const changeNextTime = data => {
  fllowUpForm.value.nextTime = data;
};
const changeNextSetting = data => {
  if (data) {
    fllowUpForm.value.nextDateTine = dayjs().format("YYYY-MM-DD HH:mm:ss");
    fllowUpForm.value.nextTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  }
};
watch(
  () => fllowUpForm.value.nextDateTine,
  (newVal, oldVal) => {
    fllowUpForm.value.nextTime = newVal;
  }
);
// 搜索人
// const searchUserLoading = ref(false);
// const searchUserList = ref([]);
// const searchUserRemoteMethod = name => {
//   if (!name) {
//     return;
//   }
//   searchUserLoading.value = true;
//   searchUser({ name })
//     .then(res => {
//       searchUserLoading.value = false;
//       searchUserList.value = res.data || [];
//     })
//     .catch(() => {
//       searchUserLoading.value = false;
//     });
// };
const handelFollowUpSubmit = () => {
  proxy.$refs.fllowUpFormRef.validate(async valid => {
    if (!valid) {
      return proxy.$modal.msgError("请完善信息");
    }
    try {
      fllowUpForm.value.crmFileCreateVOList = upImagesList.value.map(item => {
        return {
          url: item.fileUrl
        };
      });
      fllowUpForm.value.nextDateTine = dayjs(fllowUpForm.value.nextDateTine).format("YYYY-MM-DD HH:mm:ss");
      fllowUpForm.value.isNextSetting = fllowUpForm.value.isNextSetting ? 1 : 0;
      const { stageTaskId } = currentFollowTask.value;
      if (fllowUpForm.value.isNextSetting) {
        fllowUpForm.value.stageTaskId = stageTaskId;
      } else {
        if (fllowUpForm.value.hasOwnProperty("stageTaskId")) {
          delete fllowUpForm.value.stageTaskId;
        }
      }
      await addTrack(fllowUpForm.value);
      getClientInfoAndFollow();
      handelFollowUpClose();
      proxy.$modal.msgSuccess("添加成功");
    } catch (err) {
      console.log(err);
    }
  });
};
const handelFollowUpClose = async () => {
  await nextTick();
  proxy.$refs.fllowUpFormRef.resetFields();
  upImagesList.value.length = 0;
  fllowUpForm.value = {
    customerId: props.customerId,
    trackType: "",
    trackDatetime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    contentDesc: "",
    crmFileCreateVOList: [],
    isNextSetting: 0,
    nextDateTine: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    nextTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    nextContent: "",
    // nextUserIdsList: [],
    stageTaskId: ""
  };
  isFollowUp.value = false;
};

//跟进任务列表
const currentFollowTask = ref({});
const followOptions = ref([]);
const getFollowList = async () => {
  const { data } = await followTaskList(props.customerId);
  followOptions.value = data ?? [];
};
const handleTaskChange = e => {
  currentFollowTask.value = followOptions.value.find(item => item.stageTaskId === e);
};

getFllowUpType();
getDictData();
getClientInfoAndFollow();
</script>

<style scoped lang="scss">
@use "clientInfo";
</style>
